package formin.mediaLibrary.io;

import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import formin.mediaLibrary.model.SettingsData;




public class FileIO {
	
	private static final String SETTINGS_FILE_NAME = "settings.xml";
	
	private static final String PROPERTY_SQL_ADDRESS = "SQLServerAddress";
	private static final String PROPERTY_SQL_DATABASE = "SQLServerDataBase";
	private static final String PROPERTY_SQL_PASSWORD = "SQLServerPassword";
	private static final String PROPERTY_SQL_USERNAME = "SQLServerUserName";
	
	public static SettingsData readSettings(){
		FileInputStream fis;
		SettingsData settingsData = new SettingsData();
		Properties properties = new Properties();
		try {
            fis = new FileInputStream(SETTINGS_FILE_NAME);          
            properties.loadFromXML(fis);

            settingsData.setSQLServerAddress(properties.getProperty(PROPERTY_SQL_ADDRESS));
            settingsData.setSQLServerDataBase(properties.getProperty(PROPERTY_SQL_DATABASE));
            settingsData.setSQLServerPassword(properties.getProperty(PROPERTY_SQL_PASSWORD));
            settingsData.setSQLServerUserName(properties.getProperty(PROPERTY_SQL_USERNAME));
            
            fis.close();   
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	fis = null;
        }
        return settingsData;
	}

	public static void writeSettings(SettingsData settingsData){
		FileOutputStream fos;
		Properties properties = new Properties();
		
		properties.setProperty(PROPERTY_SQL_ADDRESS, settingsData.getSQLServerAddress());
		properties.setProperty(PROPERTY_SQL_DATABASE, settingsData.getSQLServerDataBase());
		properties.setProperty(PROPERTY_SQL_PASSWORD, settingsData.getSQLServerPassword());
		properties.setProperty(PROPERTY_SQL_USERNAME, settingsData.getSQLServerUserName());
		
		try{
			fos = new FileOutputStream(SETTINGS_FILE_NAME);
			properties.storeToXML(fos, "Formin Media Library Settings File", "UTF-8");
			fos.close();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			fos = null;
		}
	}
}
